<!--
/**************************************************/
/* Programmer: Stephen Chappel                    */
/*       Date:                           		  */
/*  Page Name: registration.php                   */
/*                                                */
/**************************************************/

/**************************************************/
/*                                                */
/*                                                */
/**************************************************/

/**************************************************/
/*   Date        Reviser       Revision           */
/* --------     ---------     ----------          */
/* 	  										  	  */
/*                                                */
/**************************************************/
-->

<?php

require_once('session_handler.php');
require_once('webservices.php');

session_handler_start();

function timer_api_main()
{
    if (!check_login())
        echo json_encode('NotLoggedInError');
    else
        echo json_encode(timer_api_time_left());
}

function timer_api_time_left()
{
    $connection = new mysqli($GLOBALS['SERVER_ADDRESS'], $GLOBALS['SERVER_USERNAME'], $GLOBALS['SERVER_PASSWORD'], 'cs414');
    
    $stmt = $connection->prepare('SELECT expiration FROM generic_timer WHERE email = ? ORDER BY timer_id DESC');
    $stmt->bind_param('s', $_SESSION['userid']);
    $stmt->execute();
    $result = $stmt->get_result();
    $result->data_seek(0);
    $row = $result->fetch_assoc();
    return $row['expiration'] - time();
}

function timer_api_start_countdown($seconds)
{
    if (!check_login())
        throw new Exception('User must be logged in!');
    
    $database = mysqli_connect($GLOBALS['SERVER_ADDRESS'], $GLOBALS['SERVER_USERNAME'], $GLOBALS['SERVER_PASSWORD'], 'cs414');
    
    $stmt = $datebase->prepare('INSERT INTO generic_timer (email, expiration) VALUES (?, ?);');
    $stmt->bind_param('si', $_SESSION['userid'], $seconds + time());
    $stmt->execute();
    mysqli_close($database);
}

if (!debug_backtrace())
{
    timer_api_main();
}
?>